package com.ruoyi.datam.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.base.datam.CmAddvB;
import com.ruoyi.common.core.utils.business.BusinessUtils;
import com.ruoyi.datam.mapper.WcChanBMapper;
import com.ruoyi.datam.service.IWcChanBService;
import com.ruoyi.datam.vo.IrrigatedAreaVO;
import com.ruoyi.datam.vo.WaterSupplyDistributionVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.base.datam.WcChanB;

/**
 * 渠道信息登记Service业务层处理
 *
 * @author hwd
 * @date 2023-02-16
 */
@Service
public class WcChanBServiceImpl implements IWcChanBService {
    @Autowired
    private WcChanBMapper wcChanBMapper;

    /**
     * 查询渠道信息登记
     *
     * @param chanCd 渠道信息登记主键
     * @return 渠道信息登记
     */
    @Override
    public WcChanB selectWcChanBByChanCd(String chanCd) {
        return wcChanBMapper.selectWcChanBByChanCd(chanCd);
    }

    /**
     * 查询渠道信息登记列表
     *
     * @param wcChanB 渠道信息登记
     * @return 渠道信息登记
     */
    @Override
    public List<WcChanB> selectWcChanBList(WcChanB wcChanB) {
        if(wcChanB.getChanCd()!=null){
            HashMap<String, Object> chanCodeInfo = BusinessUtils.getChanCodeInfo(wcChanB.getChanCd());
            wcChanB.setChanCd(chanCodeInfo.get("resCode")+"");
        }
        return wcChanBMapper.selectWcChanBList(wcChanB);
    }

    /**
     * 新增渠道信息登记
     *
     * @param wcChanB 渠道信息登记
     * @return 结果
     */
    @Override
    public int insertWcChanB(WcChanB wcChanB) {
        String xh ="";
        Integer count=0;
        HashMap<String, Object> chanCodeInfo =new HashMap<>();
        int grade=0;
        if (wcChanB.getParentChanCd()==null){
            wcChanB.setChanCd("CHA%000000000");
             count= wcChanBMapper.selectAllWcChanBList(wcChanB).size()+1;
        }else {
            //获取
            chanCodeInfo = BusinessUtils.getChanCodeInfo(wcChanB.getParentChanCd());
             grade = (int) chanCodeInfo.get("grade");
            String resCode = (String) chanCodeInfo.get("resCode");
            if (grade == 1) {
                //查找下属水管机构
                resCode = resCode + "%000000";
            } else if (grade == 2) {
                //查找下属水管机构
                resCode = resCode + "%000";
            } else if (grade == 3) {
                resCode = resCode + "%";
            } else {
                resCode = resCode;
            }
            wcChanB.setChanCd(resCode);
             count = wcChanBMapper.selectAllWcChanBList(wcChanB).size();
        }
         xh=count.toString();
        if(count<10){
            xh="00"+count;
        }else if (count<100){
            xh="0"+count;
        }
        if (grade==0){
            wcChanB.setChanCd("CHA"+xh+"000000000");
        }else if (grade==1){
            wcChanB.setChanCd(chanCodeInfo.get("resCode")+xh+"000000");
        }else if (grade==2){
            wcChanB.setChanCd(chanCodeInfo.get("resCode")+xh+"000");
        }else if (grade==3){
            wcChanB.setChanCd(chanCodeInfo.get("resCode")+xh);
        }else {
            return 0;
        }
        return wcChanBMapper.insertWcChanB(wcChanB);
    }

    /**
     * 修改渠道信息登记
     *
     * @param wcChanB 渠道信息登记
     * @return 结果
     */
    @Override
    public int updateWcChanB(WcChanB wcChanB) {
        return wcChanBMapper.updateWcChanB(wcChanB);
    }

    /**
     * 批量删除渠道信息登记
     *
     * @param chanCds 需要删除的渠道信息登记主键
     * @return 结果
     */
    @Override
    public int deleteWcChanBByChanCds(String[] chanCds) {
        return wcChanBMapper.deleteWcChanBByChanCds(chanCds);
    }

    /**
     * 删除渠道信息登记信息
     *
     * @param chanCd 渠道信息登记主键
     * @return 结果
     */
    @Override
    public int deleteWcChanBByChanCd(String chanCd) {
        return wcChanBMapper.deleteWcChanBByChanCd(chanCd);
    }

    /**
     * 获取渠系树形列表
     *
     * @return
     */
    @Override
    public List<WcChanB> treeList() {
        List<WcChanB> wcChanBS = wcChanBMapper.selectWcChanBList(null);
        String orgCdQuery;
        for (WcChanB vo : wcChanBS) {
            HashMap<String, Object> addvAndOrgCodeInfo = BusinessUtils.getChanCodeInfo(vo.getChanCd());
            orgCdQuery = (addvAndOrgCodeInfo.get("resCode") + "").substring(0, (addvAndOrgCodeInfo.get("resCode") + "").length() - 3);
//            WcChanB wcChanB = wcChanBMapper.selectWcChanBByChanCd((orgCdQuery + "000000000000").substring(0, 10));
            String orgCd = (orgCdQuery + "000000000000000").substring(0, 15);
            List<WcChanB> collect = wcChanBS.parallelStream().filter(vo2 -> vo2.getChanCd().equals(orgCd)).collect(Collectors.toList());
            if (collect.size() > 0 && collect.get(0) != null) {
                vo.setParentChanCd(collect.get(0).getChanCd());
            }
        }
        return wcChanBS;
    }

    @Override
    public WcChanB getlandAreaByChan(String chanCd) {
      WcChanB wcChan=  wcChanBMapper.selectWcChanBByChanCd(chanCd);
        HashMap<String, Object> addvAndOrgCodeInfo = BusinessUtils.getChanCodeInfo(chanCd);
        String resCode = (String) addvAndOrgCodeInfo.get("resCode");
       Integer grade = (int) addvAndOrgCodeInfo.get("grade");
        if (grade == 1) {
            //查找下属水管机构
            resCode = resCode + "%000000";
        } else if (grade == 2) {
            //查找下属水管机构
            resCode = resCode + "%000";
        } else if (grade == 3) {
            resCode = resCode + "%";
        } else {
            resCode = resCode;
        }
        WcChanB wcChanB= wcChanBMapper.getlandAreaByChan(resCode);
        wcChanB.setChanCd(resCode);
        List<WcChanB> wcChanBS = wcChanBMapper.selectAllWcChanBList(wcChanB);
        if (wcChanBS.size()>1){
            List<WcChanB> wcChanBList =new ArrayList<>();
            for (WcChanB v:wcChanBS
            ) {
                if (v.getChanCd().equals(chanCd)){

                }else {
                    v.setSumLandSize(wcChanBMapper.getlandAreaByChan(v.getChanCd()).getSumLandSize());
                    wcChanBList.add(v);
                }
            }
            wcChanB.setChildWcChanB(wcChanBList);
        }
        wcChanB.setChanCd(chanCd);
        wcChanB.setChanNm(wcChan.getChanNm());
       // List<WcChanB> collect = wcChanBS.parallelStream().filter(vo2 -> vo2.getChanCd().startsWith(orgCdQuery)).collect(Collectors.toList());
        return wcChanB;
    }

    @Override
    public WcChanB getChanWaterByChan(String chanCd) {
        WcChanB wcChanB= wcChanBMapper.getChanWaterByChan(chanCd);
        BigDecimal sumChanYrl =new BigDecimal(0);
        BigDecimal sumMjYrl =new BigDecimal(0);
        HashMap<String, Object> addvAndOrgCodeInfo = BusinessUtils.getChanCodeInfo(wcChanB.getChanCd());
        String resCode = (String) addvAndOrgCodeInfo.get("resCode");
        Integer grade = (int) addvAndOrgCodeInfo.get("grade");
        if (grade == 1) {
            //查找下属水管机构
            resCode = resCode + "%000000";
        } else if (grade == 2) {
            //查找下属水管机构
            resCode = resCode + "%000";
        } else if (grade == 3) {
            resCode = resCode + "%";
        } else {
            resCode = resCode;
        }
        wcChanB.setChanCd(resCode);
        List<WcChanB> wcChanBS = wcChanBMapper.selectAllWcChanBList(wcChanB);//查询下属水管机构
        if (wcChanBS.size()>1){
            List<WcChanB> wcChanBList =new ArrayList<>();
            for (WcChanB v:wcChanBS
            ) {
                if (v.getChanCd().equals(chanCd)){
                }else {
                    BigDecimal minAll = new BigDecimal(0);
                    WcChanB wcChanB1 =new WcChanB();
                    wcChanB1 =wcChanBMapper.getChanWaterByChan(v.getChanCd());//查询下属渠道取水量
                    /*查询末级渠道*/
                    HashMap<String, Object> addvAndOrgCodeInfoLast= BusinessUtils.getChanCodeInfo(wcChanB1.getChanCd());
                    String resCodeLast = (String) addvAndOrgCodeInfoLast.get("resCode");
                    Integer gradeLast = (int) addvAndOrgCodeInfoLast.get("grade");
                    if (gradeLast == 1) {
                        //查找下属水管机构
                        resCodeLast = resCodeLast + "%000000";
                    } else if (gradeLast == 2) {
                        //查找下属水管机构
                        resCodeLast = resCodeLast + "%000";
                    } else if (gradeLast == 3) {
                        resCodeLast = resCodeLast + "%";
                    } else {
                        resCodeLast = resCodeLast;
                    }
                    WcChanB wcChanBMin =new WcChanB();
                    wcChanBMin.setChanCd(resCodeLast);
                    List<WcChanB> wcChanBMinAll = wcChanBMapper.selectAllWcChanBList(wcChanBMin);
                    //查询最后一级
                    /*111111111111*/
                    if (wcChanBMinAll.size()>1) {
                        for (WcChanB min : wcChanBMinAll
                        ) {
                            WcChanB wcChanB1Last = new WcChanB();
                            wcChanB1Last = wcChanBMapper.getChanWaterByChan(min.getChanCd());//查询下属渠道取水量
                            /*查询末级渠道*/
                            HashMap<String, Object> addvAndOrgCodeInfoLastMin = BusinessUtils.getChanCodeInfo(wcChanB1.getChanCd());
                            String resCodeLastMin = (String) addvAndOrgCodeInfoLastMin.get("resCode");
                            Integer gradeLastMin = (int) addvAndOrgCodeInfoLastMin.get("grade");
                            if (gradeLastMin == 1) {
                                //查找下属水管机构
                                resCodeLastMin = resCodeLastMin + "%000000";
                            } else if (gradeLastMin == 2) {
                                //查找下属水管机构
                                resCodeLastMin = resCodeLastMin + "%000";
                            } else if (gradeLastMin == 3) {
                                resCodeLastMin = resCodeLastMin + "%";
                            } else {
                                resCodeLastMin = resCodeLastMin;
                            }
                            WcChanB wcChanBLastMin = new WcChanB();
                            wcChanBLastMin.setChanCd(resCodeLastMin);
                            List<WcChanB> wcChanBMinAllLast = wcChanBMapper.selectAllWcChanBList(wcChanBMin);
                            if (wcChanBMinAllLast.size() > 0) {
                                minAll = new BigDecimal(0);
                                for (WcChanB w : wcChanBMinAllLast
                                ) {
                                    minAll = minAll.add(wcChanBMapper.getChanWaterByChan(w.getChanCd()).getSumYrVol());
                                }
                            }
                        }
                    }


                    /*222222222222*/
                    if (wcChanBS.size()>1) {
                        for (WcChanB min : wcChanBMinAll
                        ) {
                            if (min.getChanCd().equals(resCodeLast)) {
                            } else {
                                minAll = minAll.add(wcChanBMapper.getChanWaterByChan(min.getChanCd()).getSumYrVol());
                            }
                        }
                    }
                    wcChanB1.setMjYrVol(minAll);
                    /*----------*/
                    wcChanBList.add(wcChanB1);
                    sumChanYrl=sumChanYrl.add(wcChanB1.getSumYrVol());
                    sumMjYrl=sumMjYrl.add(wcChanB1.getMjYrVol());



                }
            }
            wcChanB.setChildWcChanB(wcChanBList);

        }

        return wcChanB;
    }

    @Override
    public WaterSupplyDistributionVO waterSupplyDistribution(String chanCode) {
        WaterSupplyDistributionVO vo =wcChanBMapper.queryCurrentChannel(chanCode);   //查询渠道名称和当前渠道引水断面的水量  渠道引水断面断面类型为0
        HashMap<String, Object> chanCodeInfo = BusinessUtils.getChanCodeInfo(chanCode);
        List<WaterSupplyDistributionVO> secondChannelVolList =wcChanBMapper.querySecondChannelVol(chanCodeInfo.get("resCode")+"");//查询下级渠道的渠道引水断面的水量   渠道引水断面类型为0
        BigDecimal   secondChannelVolSum =new BigDecimal("0"); //渠道取水总量
        BigDecimal   lastChannelVolSum =new BigDecimal("0"); //末级渠系灌水水量之和
        if (secondChannelVolList.size()>0){
            secondChannelVolList.remove(0);
        }
        for (WaterSupplyDistributionVO vio: secondChannelVolList) {
            HashMap<String, Object> viochanCodeInfo = BusinessUtils.getChanCodeInfo(vio.getChanCd());
            String last=  wcChanBMapper.queryChildCurrentChannel(viochanCodeInfo.get("resCode")+"");//查询二级渠道下的所有控制断面水量
            if (last!=null){
                lastChannelVolSum.add(new BigDecimal(last));
            }else {
                last="-";
            }
            vio.setLastChannelWater(last);
            if (vio.getChannelWater()!=null){
                secondChannelVolSum.add(new BigDecimal(vio.getChannelWater()));
            }else {
                vio.setChannelWater("-");
            }
        }

        //利用系数 = 渠道取水水量之和/首部取水 保留3位小数 （6）有效利用系数为：末级渠系灌水水量之和/首部取水，保留3位小数。
        if (vo.getHeadWater()!=null){
            vo.setUtf(secondChannelVolSum.divide(new BigDecimal(vo.getHeadWater()),3,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(1000)).toString());//（5）利用系数为：渠道取水水量之和/首部取水，保留3为小数；
            vo.setEffectiveUtf(lastChannelVolSum.divide(new BigDecimal(vo.getHeadWater()),3,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(1000)).toString());//（6）有效利用系数为：末级渠系灌水水量之和/首部取水，保留3位小数。
        }else {
            vo.setHeadWater("-");
            vo.setUtf("-");
            vo.setEffectiveUtf("-");
        }
        vo.setChildrenList(secondChannelVolList);
        return vo;
    }

    @Override
    public IrrigatedAreaVO irrigatedArea(String chanCode) {
        IrrigatedAreaVO vo =wcChanBMapper.queryCurrentChanArea(chanCode);//查询渠道名称和当前渠道的灌溉面积
        HashMap<String, Object> chanCodeInfo = BusinessUtils.getChanCodeInfo(chanCode);
        List<IrrigatedAreaVO> childList=  wcChanBMapper.queryChildCurrentChanArea(chanCodeInfo.get("resCode")+"");
        if (childList.size()>0){
            childList.remove(0);
        }
        vo.setChildArea(childList);
        return vo;
    }
}
